package com.xyy.saas.payment.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
public class ExportExcelUtilBatch {

    /**
     * 初始化 HttpServletResponse
     */
    public static void initHttpResponse(HttpServletResponse response, String downFileName) throws UnsupportedEncodingException {
        response.reset();
        response.setContentType("application/msexcel");
        response.setHeader("Content-type", "application/x-xls; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(downFileName.getBytes(), "iso-8859-1"));
    }

    /**
     * 关闭缓冲流
     */
    public static void closeStream(OutputStream out, XSSFWorkbook work) throws IOException {
        if (work != null) {
            work.write(out);
            work.close();
        }
        if (null != out) {
            out.flush();
            out.close();
        }
    }

    /**
     * 写入表头
     */
    public static void writeHeader(XSSFWorkbook work, Sheet sheet, String[] headers, boolean flag) {
        CellStyle style = work.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER); // 水平方向上的对其方式
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  // 垂直方向上的对其方式
        Row header_row = sheet.createRow(0);
        int headcell_index = 0;
        if (flag) { // 有序号
            sheet.setColumnWidth(headcell_index, 1600);
            Cell headcell = header_row.createCell(headcell_index);
            // 应用样式到  单元格上
            headcell.setCellStyle(style);
            headcell.setCellValue("序号");
            headcell_index = 1;
        }
        for (int i = 0; i < headers.length; i++) {
            sheet.setColumnWidth(headcell_index, 5000);
            Cell cell = header_row.createCell(headcell_index);
            cell.setCellStyle(style);
            cell.setCellValue(headers[i]);
            headcell_index++;
        }
    }

    /**
     * 写入数据
     */
    public static int writeData(int row_index, Sheet sheet, String[] fieldNames, List dataList, boolean flag, String[] dateFormats) {
        try {
            // 插入需导出的数据
            for (int i = 0; i < dataList.size(); i++) {
                Row row = sheet.createRow(++row_index);
                row.setHeight((short) (20 * 20)); //设置行高  基数为20
                Object obj = dataList.get(i);
                Class classType = obj.getClass();
                int cell_index = 0;
                if (flag) { // 有序号
                    Cell cell = row.createCell(cell_index);
                    cell.setCellValue(row_index);
                    cell_index = 1;
                }
                for (int j = 0; j < fieldNames.length; j++) {
                    Cell cell = row.createCell(cell_index);
                    String fieldName = fieldNames[j];
                    String firstLetter = fieldName.substring(0, 1).toUpperCase();
                    String getMethodName = "get" + firstLetter + fieldName.substring(1);
                    Method getMethod = classType.getMethod(getMethodName, new Class[]{});
                    Object value = getMethod.invoke(obj, new Object[]{});
                    if (value != null) {
                        if (value instanceof Date) { // 日期类型
                            String format = "yyyy-MM-dd HH:mm";
                            if (dateFormats != null && !StringUtils.isEmpty(dateFormats[j])) {
                                format = dateFormats[j];
                            }
                            SimpleDateFormat df = new SimpleDateFormat(format);//设置日期格式
                            cell.setCellValue(df.format(value));
                        } else {
                            cell.setCellValue(value.toString());
                        }
                    }
                    cell_index++;
                }
            }
        } catch (Exception e) {
            log.error("导出数据异常:{}", e);
        }
        return row_index;
    }

}
